package study.三种方式实现生产者消费者模式.awaitAndSignal;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.LookAndFeel;

//仓库
public class Storer {
	
	private static int MAX_NUMBER=20;
	private ArrayList<Object> aList = new ArrayList<>();
	private Lock lock = new ReentrantLock();
	private Condition full = lock.newCondition();
	private Condition empty = lock.newCondition();

	public void produce (int number)
	{
//		synchronized (aList) 
//		{
		lock.lock();
			if( aList.size()+number > MAX_NUMBER )
			{
				System.out.println("需要生产的产品数量："+number+",仓库已满，停止生产！");
				try 
				{
					full.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("生产线程名字："+Thread.currentThread().getName()+"，number="+number);

			for (int i = 0; i < number; i++) {
				aList.add(new Object());
			}
			full.signalAll();
			empty.signalAll();
			lock.unlock();
//			aList.notifyAll();		
			
//		}
	}
	
	//消费者
	public void consume(int number)
	{
//		synchronized (aList) 
//		{
		lock.lock();
			if( aList.size() - number<0)
			{
				System.out.println("仓库存储不足，不能消费"+number+"个消费品！");
				try {
					empty.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("消费线程名字："+Thread.currentThread().getName()+"，number="+number);
//			if( aList.size()-number >0 )
			for (int i = 0; i < number; i++) {
				aList.remove(0);
			}
			full.signalAll();
			empty.signalAll();
			lock.unlock();
//			aList.notifyAll();
//		}
	}
}
